
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;

namespace HD
{

	public class Reflection
	{
		public static void SetFieldValue(Object obj, string key, string value)
		{
			FieldInfo fi = obj.GetType().GetField(key);
			SetFieldValue(obj, fi, value);
		}

		public static void SetFieldValue(Object obj, FieldInfo fi, string value)
		{
			if (fi.FieldType.IsEnum)
			{
                if (value.Length >0)
                {
                    fi.SetValue(obj, Enum.Parse(fi.FieldType, value));
                }				
			}
			else if (fi.FieldType == typeof(float))
			{
				fi.SetValue(obj, float.Parse(value));
			}
			else if (fi.FieldType == typeof(bool))
			{
				fi.SetValue(obj, bool.Parse(value));
			}
			else if (fi.FieldType == typeof(int))
			{
				fi.SetValue(obj, int.Parse(value));
			}
			else if (fi.FieldType == typeof(uint))
			{
				fi.SetValue(obj, uint.Parse(value));
			}
			else if (fi.FieldType == typeof(double))
			{
				fi.SetValue(obj, double.Parse(value));
			}
			else if (fi.FieldType.GetInterface(typeof(IList).ToString()) != null)
			{
				SetListValue(obj, fi, value);
			}
			else
			{
				fi.SetValue(obj, value);
			}
		}

		static void SetListValue(object obj, FieldInfo fi, string value)
		{
			if (value.Length == 0)
				return ;

			Type templateType = fi.FieldType.GetMethod("Find").ReturnType;
			IList iList = Activator.CreateInstance(fi.FieldType) as IList;

			string[] valueList = value.Trim('"').Split(',');
			foreach (string i in valueList)
			{
				if (templateType.IsEnum)
				{
					iList.Add(Enum.Parse(templateType, i));
				}
				else if (templateType == typeof(int))
				{
					iList.Add(int.Parse(i));
				}
				else if (templateType == typeof(uint))
				{
					iList.Add(uint.Parse(i));
				}
				else if (templateType == typeof(float))
				{
					iList.Add(float.Parse(i));
				}
				else if (templateType == typeof(double))
				{
					iList.Add(double.Parse(i));
				}
				else if (templateType == typeof(bool))
				{
					iList.Add(bool.Parse(i));
				}
				else{
					iList.Add(i);
				}
			}

			fi.SetValue(obj, iList);
		}
	}


} // HD